package GUI;

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;

public class MySelector {
	public static void main(String[] args) {
		MyFrame frame = new MyFrame();
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.pack();
		frame.setVisible(true);
	}
}

class MyFrame extends JFrame {
	private JButton botonOpen = new JButton("Abrir");
	private JButton botonSave = new JButton("Guardar");
	private MyFileListener myFileListener = new MyFileListener(this);

	public MyFrame() {
		super("Ejemplo de JFileChooser");
		Container container = getContentPane();
		container.setLayout(new BorderLayout());
		container.add(botonOpen, BorderLayout.WEST);
		container.add(botonSave, BorderLayout.EAST);
		botonOpen.addActionListener(myFileListener);
		botonSave.addActionListener(myFileListener);
	}
}

class MyFileListener implements ActionListener {
	private JFileChooser chooser = new JFileChooser();
	private JFrame frame;

	public MyFileListener(JFrame frame) {
		this.frame = frame;
	}

	public void actionPerformed(ActionEvent ae) {
		String textButton = ae.getActionCommand();
		String dialogTitle = "Abrir un fichero";

		if (textButton.equals("Guardar"))
			dialogTitle = "Guardar un fichero";

		chooser.setDialogTitle(dialogTitle);
		chooser.setMultiSelectionEnabled(false);
		chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);

		int sel = chooser.showOpenDialog(frame);
		if (sel == JFileChooser.APPROVE_OPTION) {
			File selectedFile = chooser.getSelectedFile();
			JOptionPane
					.showMessageDialog(frame, selectedFile.getAbsolutePath());
		} else {
			return;
		}
	}
}
